package org.ala.tiktools.sharddb.mybatis.summary.adapt;

import java.lang.reflect.Method;
import java.util.List;

import org.ala.tiktools.mybatis.pager.Pager;
import org.ala.tiktools.sharddb.mybatis.interceptor.Shard;
import org.ala.tiktools.sharddb.mybatis.summary.ICustomSummary;
import org.ala.tiktools.sharddb.mybatis.summary.ISummary;
import org.ala.tiktools.sharddb.mybatis.summary.impls.ShardListSummary;
import org.ala.tiktools.sharddb.mybatis.summary.impls.ShardPagerSummary;
import org.ala.tiktools.sharddb.mybatis.summary.impls.ShardSumSummary;
import org.ala.tiktools.tools.CachingKVTools;
import org.ala.tiktools.tools.ReflectionTools;

/**
 * 汇总器适配
 * <p>  会优先从Shard注解中拿汇总器，如果没有根据method返回值类型选择适配的
 * <p>  如果都选择不到，抛异常
 *
 * @author ala
 * @date 2025-02-21 13:11
 */
public class AdapeSummary {

	
	/**
	 *	方法对应的自定义聚合器 
	 */
	@SuppressWarnings("rawtypes")
	protected CachingKVTools<Method, ICustomSummary> summaryMapper = new CachingKVTools<Method, ICustomSummary>(ICustomSummary.NULL, m -> {
		//	检测是否有ShardSummary注解
		Shard anno = m.getAnnotation(Shard.class);
		if (anno != null && anno.summary() != null && anno.summary().length > 0) {
			return ReflectionTools.newInstance(anno.summary()[0]);
		}
		return null;
	});
	

    /**
     *  适配汇总器
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
	public <S extends ISummary> S adape(Shard anno, Method method) {
        //  如果注解中指定了汇总器，直接用
//        Class<?>[] clazzes = anno.summary();
//        if (clazzes != null && clazzes.length > 0) {
//            try {
//                return (S) TikToolsMyBatisSpringContext.getBeanOrNew(clazzes[0]);
//            } catch (InstantiationException | IllegalAccessException e) {
//                throw new ShardDBRuntimeException(e);
//            }
//        }
    	ICustomSummary summary = summaryMapper.get(method);
        if (summary != null) { return (S) summary; }

        //  否则根据method的返回值适配
        Class<?> returnType = method.getReturnType();
        return (S) adapeByType(returnType);
    }


    @SuppressWarnings("rawtypes")
	protected ISummary sum = new ShardSumSummary(),
                        list = new ShardListSummary(),
                        pager = new ShardPagerSummary();
    /**
     *  根据type进行适配
     */
    @SuppressWarnings("rawtypes")
	protected ISummary adapeByType(Class<?> returnType) {
        if (returnType.equals(Integer.TYPE)) {
            return sum;
        } else if (List.class.isAssignableFrom(returnType)) {
            return list;
        } else if (Pager.class.isAssignableFrom(returnType)) {
            return pager;
        }
        return null;
    }

}
